
#导入蓝图类
from flask import Blueprint, request, jsonify

# 导入连接数据库的组件
from public.sql_connect import get_connent

# 导入token验证的一块
from public.token import token_required, token_required_with_refresh

# 创建用户蓝图
order = Blueprint('order_print', __name__)


# 用户购买商品
@order.route('/add', methods=['POST'])
@token_required
@token_required_with_refresh
def add(current_user_id, current_user_account):
    print(current_user_id, current_user_account)
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    good_id = data.get('good_id')
    count = int(data.get('count', ''))
    if not good_id or not count:
        return jsonify({
            "code": -1,
            "msg": "缺少必要的参数",
            "data": None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 1. 先判断当前商品的库存是否够用
        cursor.execute(
            "SELECT inventory FROM goods WHERE id = %s",
            (good_id,)
        )
        good_inventory = cursor.fetchone().get('inventory')
        if int(good_inventory) < int(count):
            return jsonify({
                "code": -1,
                "msg": "购买数量太多，库存不够了",
                "data": {
                    "good_id": good_id,
                    "good_inventory": int(good_inventory)
                }
            })
        # 2. 如果库存够用就去更新去减
        cursor.execute(
            "UPDATE goods SET inventory = inventory - %s, salesCount = salesCount + %s WHERE id = %s",
            (count, count, good_id)
        )
        conn.commit()
        # 3. 创还能购买记录
        cursor.execute(
            "INSERT INTO user_goods (user_id, good_id, count, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())",
            (current_user_id, good_id, count)
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "订单创建成功",
            "data": {
                "id":cursor.lastrowid,
                "good_id": good_id,
                "count": count,
                "user_id": current_user_id,
                "userAccount": current_user_account
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 订单---确认支付
@order.route('/enter_buy/<int:order_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def enter_buy(current_user_id, current_user_account, order_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id, count, good_id FROM user_goods WHERE id = %s AND status != 'Processing'",
            (order_id,)
        )
        check_result = cursor.fetchone()
        if not check_result:
            return jsonify({
                "code": -1,
                "msg": "未找到当前订单, 或已经支付",
                "data": None
            })
        cursor.execute(
            "UPDATE user_goods SET status = 'Processing', updated_at = NOW() WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        # 接着，更新商品的销量
        cursor.execute(
            "UPDATE goods SET salesCount = salesCount + %s WHERE id = %s",
            (check_result['count'], check_result['good_id'])
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "你已完成支付",
            "data": {
                "order_id": order_id,
                "status": 'Processing',
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 订单---待收货---后台人员处理
@order.route('/shipped/<int:order_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def shipped(current_user_id, current_user_account, order_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id FROM user_goods WHERE id = %s",
            (order_id,)
        )
        check_result = cursor.fetchone()
        if not check_result:
            return jsonify({
                "code": -1,
                "msg": "未找到当前订单",
                "data": None
            })
        cursor.execute(
            "UPDATE user_goods SET status = 'Shipped', updated_at = NOW() WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "订单已成功发出",
            "data": {
                "order_id": order_id,
                "status": 'Processing',
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 订单---取消订单
@order.route('/cancel/<int:order_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def cancel(current_user_id, current_user_account, order_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id FROM user_goods WHERE id = %s",
            (order_id,)
        )
        check_result = cursor.fetchone()
        if not check_result:
            return jsonify({
                "code": -1,
                "msg": "未找到当前订单",
                "data": None
            })
        cursor.execute(
            "UPDATE user_goods SET status = 'Canceled', updated_at = NOW() WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "你已取消订单",
            "data": {
                "order_id": order_id,
                "status": 'Processing',
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 订单---确认收货
@order.route('/done/<int:order_id>', methods=['PUT'])
@token_required
@token_required_with_refresh
def done(current_user_id, current_user_account, order_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id FROM user_goods WHERE id = %s",
            (order_id,)
        )
        check_result = cursor.fetchone()
        if not check_result:
            return jsonify({
                "code": -1,
                "msg": "未找到当前订单",
                "data": None
            })
        cursor.execute(
            "UPDATE user_goods SET status = 'Commenting', updated_at = NOW() WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "你已确认收货，待评价",
            "data": {
                "order_id": order_id,
                "status": 'Processing',
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 用户购买商品后的评价商品
@order.route('/comment/<int:order_id>', methods=['POST'])
@token_required
@token_required_with_refresh
def comment(current_user_id, current_user_account, order_id):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    # good_id = data.get('good_id')
    content = data.get('content')
    picture = data.get('picture')
    # if not good_id or not content:
    #     return jsonify({
    #         "code": -1,
    #         "msg": "请提供必要的参数",
    #         "data": None
    #     })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 1. 先查看你买了没有此商品
        cursor.execute(
            "SELECT id, good_id FROM user_goods WHERE id = %s",
            (order_id,)
        )
        buy_result = cursor.fetchall()
        print("buy_result", buy_result)
        if buy_result is None:
            return jsonify({
                "code": -1,
                "msg": "你当前未购买此商品，还不能评论",
                "data": None
            })
        # 2. 创建评论记录
        cursor.execute(
            "INSERT INTO comments (content, user_id, buy_id, picture, created_at) VALUES (%s, %s, %s, %s, NOW())",
            (content, current_user_id, order_id, picture)
        )
        conn.commit()
        # 3. 更改订单状态
        cursor.execute(
            "UPDATE user_goods SET status = 'Done', updated_at = NOW() WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        # 4. 添加商品评论量
        cursor.execute(
            'UPDATE goods SET commentCount = commentCount + 1, updated_at = NOW() WHERE id = %s',
            (buy_result[0].get('good_id'),)
        )
        conn.commit()

        return jsonify({
            "code": 0,
            "msg": "评论成功,此订单已完成",
            "data": {
                "good_id": buy_result[0].get('good_id'),
                "content": content,
                "user_id": current_user_id,
                "userAccount": current_user_account,
                "order_status": "Done"
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 订单---删除订单
@order.route('/delete/<int:order_id>', methods=['DELETE'])
@token_required
@token_required_with_refresh
def delete(current_user_id, current_user_account, order_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id FROM user_goods WHERE user_id = %s AND good_id = %s",
        )
        check_result = cursor.fetchone()
        if not check_result:
            return jsonify({
                "code": -1,
                "msg": "未找到当前订单",
                "data": None
            })
        cursor.execute(
            "DELETE FROM user_goods WHERE id = %s",
            (order_id,)
        )
        conn.commit()
        return jsonify({
            "code": 0,
            "msg": "你已确认收货，此订单已完成",
            "data": {
                "order_id": order_id,
                "status": 'Processing',
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 订单---列表
@order.route('/order_list', methods=['GET'])
@token_required
@token_required_with_refresh
def order_list(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        }), 400
    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    offset = (page - 1) * page_size
    status = data.get('status', '')
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        params = [current_user_id]
        count_params = [current_user_id]
        sql = '''
        SELECT ug.id, ug.user_id, ug.good_id, ug.status, ug.created_at, ug.updated_at, ug.count,
            users.account, users.nickname, goods.name as good_name, goods.detail as good_detail,
            goods.price as good_price, goods.oldPrice as good_oldprice
        FROM user_goods ug
        LEFT JOIN users ON users.id = ug.user_id
        LEFT JOIN goods ON goods.id = ug.good_id
        WHERE ug.user_id = %s
        '''

        count_sql = '''
        SELECT COUNT(ug.id) as total_count
        FROM user_goods ug
        LEFT JOIN users ON users.id = ug.user_id
        LEFT JOIN goods ON goods.id = ug.good_id
        WHERE ug.user_id = %s
        '''
        if status:
            sql += ' AND ug.status = %s'
            count_sql += ' AND ug.status = %s'
            params.append(status)
            count_params.append(status)

        sql += ' ORDER BY ug.created_at DESC'
        sql += ' LIMIT %s OFFSET %s'
        params.extend([page_size, offset])

        cursor.execute(sql,tuple(params))
        order_list_data = cursor.fetchall()
        print("sql语句：：", sql,tuple(params))
        print("order_list_data", order_list_data)
        # 总数
        cursor.execute(count_sql,tuple(count_params))
        count = cursor.fetchone()['total_count']
        return jsonify({
            "code": 0,
            "msg": "订单列表获取成功",
            "data": {
                "order_list": order_list_data,
                "total_count": count,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()




